const swap = (arr, i, j) => {
  const temp = arr[i]
  arr[i] = arr[j]
  arr[j] = temp
}

const bubbleSort = arr => {
  let flag = true,
    // 最后一个没有经过排序的元素下标
    lastIndex = arr.length - 1,
    // 上次交换的位置
    swappedIndex = -1
  while (flag) {
    flag = false
    for (let i = 0; i < lastIndex; i++) {
      if (arr[i] > arr[i + 1]) {
        swap(arr, i, i + 1)
        flag = true
        swappedIndex = i
      }
    }
    lastIndex = swappedIndex
  }
  return arr
}

console.log(bubbleSort([4, 3, 0, 1, 2]))